/**
 * Importing the file below initializes the content script.
 *
 * Warning:
 *   Do not remove the import statement below. It is required for the extension to work.
 *   If you don't need createBridge(), leave it as "import '#q-app/bex/content'".
 */
import { createBridge } from '#q-app/bex/content'
import MediaDetector from './MediaDetector'
import AudioExtractor from './AudioExtractor'
import SpeechRecognizer from './SpeechRecognizer'
import { styles } from './styles'

class WA2TApp {
  constructor() {
    this.bridge = null
    this.mediaDetector = null
    this.audioExtractor = null
    this.speechRecognizer = null
  }

  async _initWorkflow() {
    try {
      await this.bridge.connectToBackground()
      console.log('Connected to background, portName:', this.bridge.portName)
    } catch (err) {
      console.error('Failed to connect to background:', err)
    }

    // 监听音视频检测请求
    this.bridge.on('start-detect-page-medias', async () => {
      console.log('收到音视频检测请求')
      // 检查是否为激活页面
      const isActive = await this.isActiveTab()
      if (!isActive) {
        console.log('当前页面不是激活页面，跳过检测')
        return
      }
      // 初始化并开始检测
      this.mediaDetector.startObserving()
    })

    // 监听转录开始事件
    this.bridge.on('start-transcription', async ({ payload }) => {
      // 收到转录开始事件，开始转录
      console.log('收到转录开始事件', payload.element)
      await this.startTranscription(payload.element)
    })

    // 监听转录停止事件
    this.bridge.on('stop-transcription', async () => {
      console.log('收到转录停止事件')
      await this.stopTranscription()
    })

    // 监听获取到的转录文本
    this.bridge.on('transcript-text', async (payload) => {
      console.log(payload.text)
    })
  }

  /**
   * 开始转录流程
   * @param {Object} element - 媒体元素信息
   */
  async startTranscription(element) {
    if (this.isTranscribing) {
      console.warn('转录已在进行中')
      return
    }

    try {
      this.isTranscribing = true
      console.log('开始转录流程')

      // 获取媒体元素
      const mediaElement = this.mediaDetector.getElementBySrc(element.src)
      if (!mediaElement) {
        throw new Error('未找到对应的媒体元素')
      }

      // 初始化语音识别器
      if (!this.speechRecognizer) {
        this.speechRecognizer = new SpeechRecognizer()
        await this.speechRecognizer.initialize({
          // 使用绝对路径，让SpeechRecognizer自己处理路径构建
          modelPath: null,
          onProgress: (progress) => {
            console.log('语音识别进度:', progress)
            // 向background发送进度信息
            this.bridge.send({
              event: 'transcription-progress',
              to: 'background',
              payload: progress,
            })
          },
          onResult: (result) => {
            console.log('语音识别结果:', result)
            // 向background发送识别结果
            this.bridge.send({
              event: 'transcription-result',
              to: 'background',
              payload: result,
            })
          },
          onError: (error) => {
            console.error('语音识别错误:', error)
            // 向background发送错误信息
            this.bridge.send({
              event: 'transcription-error',
              to: 'background',
              payload: { error: error.message },
            })
          },
          onComplete: (complete) => {
            console.log('语音识别完成:', complete)
            // 向background发送完成信息
            this.bridge.send({
              event: 'transcription-complete',
              to: 'background',
              payload: complete,
            })
            this.isTranscribing = false
          },
        })
      }

      // 开始语音识别
      const success = await this.speechRecognizer.startRecognition(element)
      if (!success) {
        throw new Error('语音识别启动失败')
      }

      console.log('转录流程启动成功')
    } catch (error) {
      console.error('转录流程启动失败:', error)
      this.isTranscribing = false

      // 向background发送错误信息
      this.bridge.send({
        event: 'transcription-error',
        to: 'background',
        payload: { error: error.message },
      })
    }
  }

  /**
   * 停止转录流程
   */
  async stopTranscription() {
    if (!this.isTranscribing) {
      console.warn('转录未在进行中')
      return
    }

    try {
      console.log('停止转录流程')

      if (this.speechRecognizer) {
        this.speechRecognizer.stopRecognition()
      }

      this.isTranscribing = false
      console.log('转录流程已停止')
    } catch (error) {
      console.error('停止转录流程失败:', error)
    }
  }

  async init() {
    this.bridge = createBridge({ debug: false })
    this.mediaDetector = new MediaDetector(this.bridge)
    this.audioExtractor = new AudioExtractor()
    await this._initWorkflow()
  }

  static async create() {
    const instance = new WA2TApp()
    await instance.init()
    return instance
  }

  cleanup() {
    if (this.mediaDetector) {
      this.mediaDetector.stopObserving()
      this.mediaDetector = null
    }
    if (this.audioExtractor) {
      this.audioExtractor.cleanup()
      this.audioExtractor = null
    }
    if (this.speechRecognizer) {
      this.speechRecognizer.destroy()
      this.speechRecognizer = null
    }
    this.isTranscribing = false
  }

  async isActiveTab() {
    try {
      // 通过 bridge 向 background 请求当前标签页信息
      const tab = await this.bridge.send({ event: 'get-active-tab', to: 'background' })
      // 检查当前页面 URL 是否匹配
      return tab && tab.url === window.location.href
    } catch (error) {
      console.error('检查页面激活状态失败:', error)
      return false
    }
  }
}

// 页面载入时添加样式
window.addEventListener('load', () => {
  const style = document.createElement('style')
  style.textContent = styles
  document.head.appendChild(style)
})

// 创建实例
WA2TApp.create()
  .then((wa2tApp) => {
    console.log('WA2TApp created')
    // 监听页面卸载事件
    window.addEventListener('unload', () => {
      wa2tApp.cleanup()
      this.bridge.send({
        event: 'stop-detect-page-medias',
        to: 'background',
        payload: { url: window.location.href },
      })
    })
  })
  .catch((err) => {
    console.error('Failed to create WA2TApp:', err)
  })
